<%-- 
  - Author: Jordi Vilaplana Mayoral <jvilaplana@alumnes.udl.cat>
  - Date: 05/04/2011
  - 
  - LocationManager
  - Copyright (C) 2011 Jordi Vilaplana Mayoral
  -
  - This program is free software: you can redistribute it and/or modify
  - it under the terms of the GNU General Public License as published by
  - the Free Software Foundation, either version 3 of the License, or
  - (at your option) any later version.
  -
  - This program is distributed in the hope that it will be useful,
  - but WITHOUT ANY WARRANTY; without even the implied warranty of
  - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  - GNU General Public License for more details.
  -
  - You should have received a copy of the GNU General Public License
  - along with this program.  If not, see <http://www.gnu.org/licenses/>.
  - 
  - @(#)
  - Description: This program allows users to book rooms and schedule activities
  --%>

<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<h2>Nova activitat</h2>

<c:choose>
  <c:when test="${requestScope.success == true}">
    <p class="info" id="newLocSuccess" onclick="$('newLocSuccess').hide();">Espai inserit correctament.</p>
  </c:when>
</c:choose>

<form name="createNewActivity" action="NewActivity" class="newLoc" method="post">

  <div class="newLocActivityInfo">

    <fieldset>

      <legend>Dades de l'activitat</legend>

      <br />

      <label for="publicName">Nom:</label>
      <input id="publicName" class="long" autofocus name="publicName" placeholder="Nom de l'activitat" type="text" />
      <br /><br />
      <div class="left">

        <label for="managerId">Responsable:</label>
        <input id="managerId" type="text" name="managerId" value="${sessionScope.userName}" disabled />
        <br /><br />
        <label for="maxStudents">Màxim matriculats:</label>
        <input oninput="filterLocations()" id="maxStudents" name="maxStudents" type="number" min="0" max="999" step="5" value="20" />
        <br /><br />
        <label for="roomTypeId">Tipus de sala:</label>
        <select onchange="filterLocations()" id="roomTypeId" size="5" name="roomTypeId">
          <c:forEach var="roomType" items="${requestScope.roomTypeList}">
            <option value="${roomType.roomTypeId}">
              <c:out value="${roomType.typeName}" />
            </option>
          </c:forEach>
        </select>
      </div>

      <div class="right">

        <label for="duration">Duració:</label>
        <input oninput="filterLocations()" id="duration" name="duration" type="number" min="0" max="99" step="1" value="1" /> (hores)
        <br /><br />
        <label for="startDate">Dia d'inici:</label>
        <input oninput="filterLocations()" id="startDate" type="date" name="startDate" required="required" /> (aaaa/mm/dd)
        <br /><br />
        <label for="locationEquipments">Equipaments:</label>
        <select id="locationEquipments" size="5" multiple name="locationEquipments">
          <c:forEach var="equipment" items="${requestScope.equipmentList}">
            <option value="${equipment.equipmentId}">
              <c:out value="${equipment.publicName}" />
            </option>
          </c:forEach>
        </select>

      </div>

    </fieldset>
    <script>

    </script>

  </div>

  <div class="newLocLocationList">

    <fieldset>
      <legend>Ubicacions disponibles</legend>
      <div id="availableLocations">
      </div>
    </fieldset>

  </div>

  <div class="newLocActivitySchedule">

    <fieldset>
      <legend>Horari</legend>
      <div id="locationSchedule">
      </div>
    </fieldset>

  </div>

  <br /><br />
  <input class="newActivity" type="submit" value="Nova Activitat" />
</form>

<script>
  
  // Get current date in dd/mm/yyyy format
  var now = new Date();
  var day = now.getDate();
  if(day < 10) day = "0" + day;
  var month = now.getMonth() + 1;
  if(month < 10) month = "0" + month;
  var year = now.getFullYear();
  var today = year + "-" + month + "-" + day;
  $('startDate').value = today;



  Element.addMethods("select", (function() {
    function getSelectedOptionHTML(element) {
      if (!(element = $(element))) return;
      var index = element.selectedIndex;
      return index >= 0 ? element.options[index].value : undefined;
    }

    return {
      getSelectedOptionHTML: getSelectedOptionHTML
    };
  })());

  function filterLocations() {

    var selectedEquipments = new Array();
    for (var i = 0; i < $('locationEquipments').options.length; i++)
      if ($('locationEquipments').options[ i ].selected)
        selectedEquipments.push($('locationEquipments').options[ i ].value);

    new Ajax.Request('LocationFilter', {
      method:'post',
      parameters: {
        'maxStudents': $('maxStudents').value,
        'duration': $('duration').value,
        'startDate': $('startDate').value,
        'roomTypeId': $('roomTypeId').getSelectedOptionHTML(),
        'locationEquipments' : selectedEquipments
      },
      onSuccess: function(transport, json) {
        var response = transport.responseText;
        json = response.toJSON();
        var data = json.evalJSON();

  ${'availableLocations'}.update('');
          data.each(function(location) {
          
            getVarClass(location.locationId, location.publicName);
          
          

          
          
          
            //          var newElement = '<p><input onclick="showLocationSchedule()" type="radio" name="locationId" value="' + location.locationId + '" />' + location.publicName + '</p>';
            //          var newContent = ${'availableLocations'}.innerHTML + newElement;
            //  ${'availableLocations'}.update(newContent);
            //    ${'locationSchedule'}.update('');
          });

        }
      });
    }

    function getVarClass(locationId, publicName) {
      new Ajax.Request('CheckLocationSchedule', {
        method:'post',
        parameters: {
          'locationId': locationId,
          'duration': $('duration').value,
          'startDate': $('startDate').value
        },
        onSuccess: function(transport) {
          this.response = transport.responseText || "";
          this.alertFunction(locationId, publicName);
        }.bind(this),
        onFailure: function() { alert('merda') }
      });
    
    }

    function alertFunction(locationId, publicName) {
      var pclass = "";
      var nextDate = "";
      var disabled = "";
      if(this.response != "") {
        pclass = 'class="error"';
        nextDate = ' (' + this.response + ')';
        disabled = ' disabled = "disabled"';
      }
      var newElement = '<p ' + pclass + '><input' + disabled + ' onclick="showLocationSchedule()" type="radio" name="locationId" value="' + locationId + '" />' + publicName + nextDate + '</p>';
      var newContent = ${'availableLocations'}.innerHTML + newElement;
  ${'availableLocations'}.update(newContent);
  ${'locationSchedule'}.update('');
  
      }

      function showLocationSchedule() {

        var radioGrp = document['forms']['createNewActivity']['locationId'];
        for(i=0; i < radioGrp.length; i++){
          if (radioGrp[i].checked == true) {
            var radioValue = radioGrp[i].value;
          }
        }



        new Ajax.Request('LocationSchedule', {
          method:'post',
          parameters: {
            'locationId': radioValue,
            'duration': $('duration').value,
            'startDate': $('startDate').value
          },
          onSuccess: function(transport, json) {
            var response = transport.responseText;
            json = response.toJSON();
            var data = json.evalJSON();

  ${'locationSchedule'}.update('');
                var newContent = "Pot reservar aquesta sala de " + data + ":00 a " + (parseInt(data) + parseInt($('duration').value)) + ":00 hores.";
  ${'locationSchedule'}.update(newContent);


        }
      });


    }

    //  function filterLocations() {
    //
    //    var test = $$('#locationList option').find(function(ele){return !!ele.selected});
    //
    //    var id = test.value;
    //
    //    new Ajax.Request('LocationFilter',
    //    {
    //      method:'post',
    //      parameters: {
    //        'maxStudents': $$('#maxStudents')
    //      },
    //      onSuccess: function(transport, json) {
    //        var response = transport.responseText;
    //        json = response.toJSON();
    //        //alert(json ? Object.inspect(json) : "no JSON object");
    //        var data = json.evalJSON();
    //
    //  ${'publicName'}.value = data.publicName;
    //  ${'roomTypeId'}.value = data.roomTypeId;
    //  ${'capacity'}.value = data.capacity;
    //  ${'locationId'}.value = data.locationId;
    //
    //
    //        var options = $$('select#equipmentList option');
    //        var len = options.length;
    //        for (var i = 0; i < len; i++) {
    //          options[i].selected = false;
    //        }
    //
    //        data.equipments.each(function(equipment) {
    //
    //          for (var i = 0; i < len; i++) {
    //            if(options[i].value == equipment.equipmentId) options[i].selected = true;
    //          }
    //
    //        });
    //
    //
    //      }
    //    });
    //  }


    filterLocations();



</script>